package top.infopub.mgr.mkt.web;


import com.github.pagehelper.Page;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import top.infopub.enums.mkt.ProProcesssStatusEnum;
import top.infopub.mgr.common.page.ParamPage;
import top.infopub.mgr.common.vo.ErrorCodeEnum;
import top.infopub.mgr.common.vo.RspVo;
import top.infopub.mgr.flow.web.GenericFlowController;
import top.infopub.mgr.hr.service.StaffInfoService;
import top.infopub.mgr.mkt.domain.BidBondApplyDomain;
import top.infopub.mgr.mkt.service.BidBondApplyService;
import top.infopub.mgr.mkt.service.InquiryProService;
import top.infopub.mgr.mkt.service.ProProcessManageService;
import top.infopub.mgr.mkt.vo.BidBondApplyVo;
import top.infopub.mgr.sg.service.CoopInfoService;
import top.infopub.mgr.util.FileHelper;
import top.infopub.mgr.util.LogUtil;
import top.infopub.mgr.util.LogUtil.AcctionType;
import top.infopub.mgr.util.LogUtil.LogModelType;
import top.infopub.model.hr.StaffInfo;
import top.infopub.model.mkt.BidBondApply;
import top.infopub.model.mkt.BidBondAtt;
import top.infopub.model.mkt.InquiryPro;
import top.infopub.model.sg.CoopInfo;
import top.infopub.security.util.SessionUserUtils;
import top.infopub.security.vo.AuthorizationVO;
import top.infopub.tdp.sys.service.CodeGeneratorConfigService;
import top.infopub.util.IdFactory;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 投标保证金申请管理
 * @author wangw
 * @version 2020年1月9日
 * @see BidBondApplyController
 * @since
 */
@Controller
@RequestMapping("/bidBondApply")
public class BidBondApplyController extends GenericFlowController {

    @Autowired
    private BidBondApplyService bidBondApplyService;

    @Autowired
    private ProProcessManageService proProcessManageService;

    @Autowired
    private InquiryProService inquiryProService;

    @Autowired
    private StaffInfoService staffInfoService;

    @Autowired
    private CoopInfoService coopInfoService;

    @Autowired
    private CodeGeneratorConfigService codeGeneratorConfigService;

    /**
     * 投标保证金申请详情跳转
     * @return
     */
    @RequestMapping("/toDealOrDetailApply")
    public String toDealOrDetailApply(HttpServletRequest request,String id,String proCode,String bondType) {
        request.setAttribute("proCode", proCode);
        request.setAttribute("id", id);
        request.setAttribute("bondType", bondType);
        request.setAttribute("isAuditFlag", "0");
        BidBondApply bidBondApply  = bidBondApplyService.selectByKey(id);
        if (bidBondApply != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidBondApply.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "1");
            }
            if (StringUtils.isNotBlank(bidBondApply.getProcessId()) && bidBondApply.getProcessId().length() > 10) {
                request.setAttribute("processId", bidBondApply.getProcessId());
            }
        }
        return "mkt/lay-marginPayment-detail";
    }

    /**
     * 投标保证金申请列表数据
     * @return
     */
    @RequestMapping("/queryDataByCondition")
    @ResponseBody
    public RspVo<BidBondApplyDomain> queryDataByCondition(BidBondApplyVo bidBondApplyVo, ParamPage paramPage) throws ParseException {
        Page<BidBondApplyDomain> page = new Page<BidBondApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //处理时间范围
        if (!StringUtils.isEmpty(bidBondApplyVo.getDates()))
        {
            String[] splitTime = bidBondApplyVo.getDates().split("~");
            SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
            bidBondApplyVo.setStartDate(format.parse(splitTime[0]));
            bidBondApplyVo.setEndDate(format.parse(splitTime[1]));
        }

        page = bidBondApplyService.selectPageByDomainWhere(page, bidBondApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 投标保证金申请-我审批的列表数据
     * @return
     */
    @RequestMapping("/queryMyCheckDataByCondition")
    @ResponseBody
    public RspVo<BidBondApplyDomain> queryMyCheckDataByCondition(BidBondApplyVo bidBondApplyVo, ParamPage paramPage) {
        Page<BidBondApplyDomain> page = new Page<BidBondApplyDomain>();
        page.setPageNum(paramPage.getPage());
        page.setPageSize(paramPage.getLimit());
        //查询时，结束日期增加一天
        if (bidBondApplyVo.getEndDate() != null) {
            bidBondApplyVo.setEndDate(DateUtils.addDays(bidBondApplyVo.getEndDate(), 1));
        }
        //查询时，投标截止日结束日期增加一天
        if (bidBondApplyVo.getBidEndDateEndDate() != null) {
            bidBondApplyVo.setBidEndDateEndDate(DateUtils.addDays(bidBondApplyVo.getBidEndDateEndDate(), 1));
        }
        bidBondApplyVo.setAddBy(SessionUserUtils.getSessionUserId());
        page = bidBondApplyService.selectMyCheckByDomainWhere(page, bidBondApplyVo);
        return RspVo.getSuccessResponse(page.getTotal(), page.getResult());
    }

    /**
     * 投标保证金申请-新增
     * @return
     */
    @RequestMapping("/add")
    public String add(HttpServletRequest request) {
        //查询可投标保证金申请的立项通过记录
        InquiryPro inquiryPro = new InquiryPro();
        inquiryPro.setProcessStatus("9");
        List<InquiryPro> inquiryPros = inquiryProService.selectByEntityWhere(inquiryPro);
        request.setAttribute("inquiryPros", inquiryPros);
        //查询可用的联合体单位记录
        CoopInfo coopInfo = new CoopInfo();
        coopInfo.setState(1);
        coopInfo.setTypes("1");
        List<CoopInfo> coopInfos = coopInfoService.selectByEntityWhere(coopInfo);
        request.setAttribute("coopInfos", coopInfos);
        return "mkt/lay-bidBondApply-add";
    }

    /**
     * 根据id查询投标保证金申请详情  > 注意：方法命名必须为：toDealOrDetail
     * @param id 投标保证金申请Id
     * @return
     * @see
     */
    @RequestMapping("/toDealOrDetail")
    public String queryById(HttpServletRequest request,String id, String proCode,String bondType) {
        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();
        request.setAttribute("proCode", proCode);
        request.setAttribute("bondType", bondType);
        request.setAttribute("id", id);
        request.setAttribute("isAuditFlag", "1");
        request.setAttribute("auditTabFlag", "0");
        BidBondApply bidBondApply  = bidBondApplyService.selectByKey(id);
        if (bondType==null){
            request.setAttribute("bondType", bidBondApply.getBondType());
        }
        if (bidBondApply != null) {
            if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidBondApply.getProcessStatus())
                    || StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS9.getCode(), bidBondApply.getProcessStatus())) {
                request.setAttribute("isAuditFlag", "0");
            }
            if (StringUtils.isNotBlank(bidBondApply.getProcessId()) && bidBondApply.getProcessId().length() > 10) {
                request.setAttribute("processId", bidBondApply.getProcessId());
                String auditTabFlag = proProcessManageService.checkShowAuditTab(bidBondApply.getProcessId(), vo);
                if (StringUtils.equals(ProProcesssStatusEnum.PRO_STATUS1.getCode(), bidBondApply.getProcessStatus())
                        && StringUtils.equals("0", auditTabFlag)) {
                    request.setAttribute("isAuditFlag", "0");
                }
                request.setAttribute("auditTabFlag", auditTabFlag);
            }
        }
        return "mkt/lay-marginPayment-detail";
    }

    //审批
    @RequestMapping("/auditProcess")
    @ResponseBody
    public RspVo auditProcess(String id, String processId, String status, String auditMsg) {
        //立项审批
        proProcessManageService.auditProject(id, processId, status, auditMsg, null);
        return RspVo.getSuccessResponse();
    }
    /**
     * 新增投标保证金申请
     * @return
     */
    @SuppressWarnings({"rawtypes"})
    @RequestMapping("/save")
    public @ResponseBody RspVo save(HttpServletRequest request,BidBondApplyVo bidBondApply) {
        String[] fileAtt = request.getParameterValues("fileAtt");

        AuthorizationVO vo = SessionUserUtils.getSessionAttributeForUserDtl();

        /**
         * 投标保证金申请主表处理
         */
        String id = IdFactory.getUUIDUpper();
        bidBondApply.setId(id);
        bidBondApply.setHrStaffApplyId(vo.getHrStaffId());
        bidBondApply.setHrOrgId(bidBondApply.getApplyOrgId());
        bidBondApply.setHrDeptId(bidBondApply.getApplyDeptId());
        bidBondApply.setBidEndDate(bidBondApply.getApplyBidEndDate());
        bidBondApply.setBondEndDate(bidBondApply.getApplyBondEndDate());
        bidBondApply.setBondMoney(bidBondApply.getApplyBondMoney());
        StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(vo.getHrStaffId());
        bidBondApply.setStaffName(staffInfo.getStaffName());
        bidBondApply.setAddBy(vo.getId());
        bidBondApply.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());
        String codes = codeGeneratorConfigService.generatorCode("mkt_bid_bond_apply_codes");
        bidBondApply.setCodes(codes);
        // 处理processId
        bidBondApply.setProcessId(IdFactory.getUUIDUpper());
        bidBondApply.setProcessStatus("1");//审批中
        bidBondApply.setUptBy(vo.getId());
        bidBondApply.setUptTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());

        /**
         * 上传的文件记录加入集合
         */
        List<BidBondAtt> bidBondAtts = new ArrayList<BidBondAtt>();
        //项目可研报告
        if(fileAtt != null){
            for(String file : fileAtt){
                BidBondAtt bidBondAtt = createFileAtt(vo, id, file);
                bidBondAtts.add(bidBondAtt);
            }
        }
        bidBondApplyService.addBidBondApply(bidBondApply, bidBondAtts);
        LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "投标保证金申请 -新增投标保证金申请：项目名="+bidBondApply.getProName(), null);
        return RspVo.getSuccessResponse();
    }

    private BidBondAtt createFileAtt(AuthorizationVO vo, String applyId, String file) {
        //资料信息数组
        String[] fileAttStr = file.split("\\|");
        BidBondAtt fileAtt = new BidBondAtt();
        fileAtt.setId(fileAttStr[1]);
        fileAtt.setApplyId(applyId);//项目id
        String fileName = fileAttStr[0].substring(0,fileAttStr[0].lastIndexOf("."));
        String suffix = fileAttStr[0].substring(fileAttStr[0].lastIndexOf("."),fileAttStr[0].length()).toLowerCase();//后缀转小写
        fileAtt.setFileName(fileName);//文件名
        fileAtt.setFileSuffix(suffix);//文件后缀
        fileAtt.setFilePath(fileAttStr[2]);//文件保存路径
        fileAtt.setAddBy(vo.getId());//添加人
        fileAtt.setAddTime(top.infopub.mgr.util.DateUtils.getCurrentDateTime());//添加时间
        return fileAtt;
    }
    /**
     * 根据id查询投标保证金申请记录
     * @param id
     * @return
     * @throws Exception
     */
    @RequestMapping("/getBidBondApplyById")
    @ResponseBody
    public Map<String, Object> getBidBondApplyById(String id) {
        boolean flag = true;
        Map<String, Object> map = new HashMap<String, Object>();
        try {
            BidBondApplyVo bidBondApplyVo = bidBondApplyService.selectById(id);
            AuthorizationVO authorizationVO = SessionUserUtils.getSessionAttributeForUserDtl();
            StaffInfo staffInfo = staffInfoService.selectByPrimaryKey(authorizationVO.getHrStaffId());
            bidBondApplyVo.setStaffName(staffInfo.getStaffName());
            map.put("bidBondApplyVo", bidBondApplyVo);
        }
        catch (Exception e) {
            log.error("查询投标保证金申请记录异常", e);
            flag = false;
        }
        map.put("flag", flag);
        return map;
    }

    /**
     * 上传附件
     * @param request
     * @return
     * @throws IOException
     * @see
     */
    @SuppressWarnings("rawtypes")
    @RequestMapping("/uploadAtt")
    public @ResponseBody RspVo uploadAtt(HttpServletRequest request)
        throws IOException {
        List<String> returnFileStrList = new ArrayList<>();
        MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest)request;
        Map<String, MultipartFile> map = multipartHttpServletRequest.getFileMap();
        if (map != null) {
            for (String name : map.keySet()) {
                MultipartFile file = map.get(name);
                if (file == null) {
                    return ErrorCodeEnum.ERROR_COMMON_PARAM.getRspVo("上传文件不能为空");
                }
                // 上传文件
                String fileId = IdFactory.getUUIDSerialNumber();
                // 服务器资源路径
                String serverPath = "bidBondAtt";
                String filePath = FileHelper.upload(file, serverPath);
                returnFileStrList.add(file.getOriginalFilename().trim() + "|" + fileId + "|"
                                      + filePath);
                LogUtil.bizLog(LogModelType.PROJECT, AcctionType.ADD, "上传资格预审附件-文件名:" + filePath
                                                                      + "，文件路径:" + filePath, null);
            }
        }
        return RspVo.getSuccessResponse(returnFileStrList);
    }
}
